<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/10/17
 * Time: 15:07
 */
namespace App\Http\Admin\Product\Controllers;

use App\Eloquent\Ygt\CategoryFields;
use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Website\Models\Menu;
use App\Eloquent\Ygt\Category;
use App\Eloquent\Ygt\ProductFields;
use App\Http\Admin\Product\Models\Product;
use App\Engine\Func;
use App\Engine\Product as EngineProduct;
use App\Engine\Dictionary;
use Excel;
use PHPExcel_Worksheet_Drawing;

class IndexController extends Controller
{
    protected $modelName = 'Product';
    protected $company = true;

    public function __construct()
    {
        parent::__construct();
        $this->model = new Product();

    }

    public function getProductList()
    {
        $adminUser = request()->user('admin')->toArray();
        $company_id = $adminUser['company_id'];
        if (request()->isMethod('post')) {
            $where = [];
            if ($categoryId = request('category_id')) {
                $categoryIds = explode(',', $categoryId);
                foreach ($categoryIds as $v) {
                    $categoryModel = new Category();
                    $categoryArr = $categoryModel->getCategoryOption($v,$company_id);
                    $category = collect($categoryArr);

                    $tempCategoryIds = $category->map(function ($c) {
                        return $c['id'];
                    })->toArray();
                    $categoryIds = array_merge($categoryIds, $tempCategoryIds);
                }
                $categoryIds = array_unique($categoryIds);
                $where['category_id'] = ['in', $categoryIds];
            }

            if ($productName = request('product_name')) {
                $where['product_name'] = ['like', '%' . $productName . '%'];
            }

            if ($productNo = request('product_no')) {
                $where['product_no'] = $productNo;
            }

            if ($isPublic = request('is_public')) {
                $where['is_public'] = $isPublic;
            }

            $where['company_id'] = $company_id;

            $pageSize = request('pageSize', 30);
            $pageCurrent = request('pageCurrent', 1);
            $offset = ($pageCurrent - 1) * $pageSize;

            $productModel = new Product();
//            $productResult = $productModel->getProList($where, 'ygt_product.*', $pageSize, $offset);
            $orderBy = ['ygt_product.id', 'desc'];
            $join = [
                ['table' => 'ygt_img_upload', 'field_l' => 'ygt_product.img_id', 'field_c' => '=', 'field_r' => 'ygt_img_upload.id'],
            ];
            $productResult = $productModel->getData($where, 'ygt_product.*', $pageSize, $offset, $orderBy, '', $join);

            $productResult->transform(function ($item, $key) {
                $item->img_url = Func::getImgUrlById($item->img_id);
                $item->qrcode = EngineProduct::getProductQrcode($item->product_no);
                return $item;
            });

            $count = $productModel->getCount($where);

            $result = collect(['totalRow' => $count, 'pageCurrent' => $pageCurrent, 'list' => $productResult]);
            return $result->toJson();
        }

        $categoryModel = new Category();
        $category = $categoryModel->getCategoryOption(0,$company_id);
        $catelist = [];
        foreach ($category as $k => $v) {
            $catelist[$v['id']] = str_repeat('└―', $v['level']) . $v['cat_name'];
        }
        $optionHtml = '';
        foreach ($catelist as $k => $v) {
            $optionHtml .= '<option value="' . $k . '">' . $v . '</option>';
        }
        $catejson = json_encode($catelist);

        return $this->view('list', compact('catejson', 'optionHtml'));
    }

    public function addProduct()
    {
        $adminUser = request()->user('admin')->toArray();
        $company_id = $adminUser['company_id'];

        if (request()->isMethod('post')) {

            $params = request()->only('product_name', 'product_no', 'warning_number', 'full_number', 'category_id', 'img_id', 'price', 'unit', 'weight', 'spec','is_public');
            $params['product_no'] = $params['product_no']?$params['product_no']:EngineProduct::createProductNo();

            $rules = [
                'warning_number' => 'required|integer',
                'full_number' => 'required|integer',
            ];
            $this->validateRequestParameters($params, $rules);

            foreach ($params as $key => $val) {
                if (!is_null($val)) {
                    $createData[$key] = $val;
                }
            }

            $createData['company_id'] = $company_id;
            $productModel = new Product();
            if(!$productModel->getOneData(['product_no'=>$params['product_no']])){
                if ($productId = $productModel->insertOneData($createData,'id')) {

                    $fields = request()->only('customer_field_name','customer_field_type','customer_field_value');
                    if($fields['customer_field_type']){
                        $ProductFieldsModel = new ProductFields();
                        $fieldsData = [];
                        foreach ($fields['customer_field_type'] as $key => $val){
                            $comumnName = EngineProduct::getFieldColumn($val);
                            $fieldsData[] = [
                                'product_id' => $productId,
                                'field_name' => $fields['customer_field_name'][$key],
                                'field_type' => $val,
                                $comumnName => $fields['customer_field_value'][$key]
                            ];
                        }
                        $ProductFieldsModel->insertData($fieldsData);
                    }


                    return $this->ajaxSuccess();
                } else {
                    return $this->ajaxFail();
                }
            }else{
                return $this->ajaxFail('材料编号已存在！');
            }


        }
        $categoryModel = new Category();
        $category = $categoryModel->getCategoryOption(0,$company_id);
        $catelist = [];
        foreach ($category as $k => $v) {
            $catelist[$v['id']] = str_repeat('└―', $v['level']) . $v['cat_name'];
        }

        $categoryId = request('category_id');

        $categoryInfo = $categoryModel->getOneData(['id'=>$categoryId]);

        $categoryFieldsModel = new CategoryFields();
        $categoryFields = $categoryFieldsModel->getData(['category_id'=>$categoryId]);
        //单位列表
        $units = Dictionary::getUnitList()->toArray();
        return $this->view('add', compact('catelist', 'units', 'categoryFields', 'categoryInfo'));
    }

    public function editProduct()
    {
        $adminUser = request()->user('admin')->toArray();
        $company_id = $adminUser['company_id'];
        if (request()->isMethod('post')) {

            $params = request()->only('product_name', 'product_no', 'barcode', 'warning_number', 'full_number', 'category_id', 'img_id', 'price', 'unit', 'weight', 'spec','is_public');
            $where = ['id' => request('id')];
            foreach ($params as $key => $val) {
                if (!is_null($val)) {
                    $createData[$key] = $val;
                }
            }
            $productModel = new Product();
            if ($result = $productModel->updateOneData($where, $createData)) {
                return $this->ajaxSuccess('保存成功');
            } else {
                return $this->ajaxFail('保存失败');
            }
        }
        $id = request('id');
        $productModel = new Product();
        $where = ['id' => $id];
        $info = $productModel->getOneData($where);
        $info->img_url = Func::getImgUrlById($info->img_id);

        //分类列表
        $categoryModel = new Category();
        $category = $categoryModel->getCategoryOption(0,$company_id);
        $catelist = [];
        foreach ($category as $k => $v) {
            $catelist[$v['id']] = str_repeat('└―', $v['level']) . $v['cat_name'];
        }

        //单位列表
        $units = Dictionary::getUnitList()->toArray();

        return $this->view('edit', compact('info', 'catelist', 'units'));

    }


    public function saveProduct(Request $request)
    {
        $params = $this->jsonRequest();
        $input = $request->all();
        try {
            $user = new Product();
            $result = (isset($input['addFlag']) && $input['addFlag'])
                ? $user->addProduct($input)
                : $user->updateProduct($input);
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }

        return $this->jsonReturn($result);
    }


    public function delProduct()
    {
        $id = request('id');
        $productModel = new Product();
        $result = $productModel->where('id', $id)->delete();
        if ($result) {
            return $this->ajaxSuccess('删除成功');
        } else {
            return $this->ajaxFail('删除失败');
        }
    }


    /**
     * 产品属性列表
     */
    public function attrList()
    {
        $productId = request('product_id');
        if (request()->isMethod('post')) {

            $list = ProductFields::where('product_id', $productId)->get();
            $list->transform(function($item){
                $comumnName = EngineProduct::getFieldColumn($item->field_type);
                $item->field_value = $item->$comumnName;
                return $item;
            });
            return $list;
        }

        $fieldsType = EngineProduct::fieldsType();
        foreach ($fieldsType as $k => $v) {
            $fieldsType[$k] = $v['title'];
        }

        $fieldsType = json_encode($fieldsType);

        return $this->view('attr-list', compact('fieldsType', 'productId'));

    }

    public function attrSave()
    {
        $param = $this->requestJson();

        $productId = request('product_id');
        $data = [
            'product_id' => $productId,
            'field_name' => $param['field_name'],
            'field_type' => $param['field_type'],
        ];

        $FieldColumn = EngineProduct::getFieldColumn($param['field_type']);
        $data[$FieldColumn] = $param['field_value'];

        $ProductFieldsModel = new ProductFields();
        if (isset($param['addFlag'])) {
            $result = $ProductFieldsModel->insertData($data);
        } else {
            $where = ['id' => $param['id']];
            $result = $ProductFieldsModel->updateOneData($where, $data);
        }
        if($result){
            return $this->ajaxSuccess();
        }else{
            return $this->ajaxFail();
        }

    }

    public function attrDelete(){
        $ProductFieldsModel = new ProductFields();
        $where = ['id'=>request('id')];
        $result = $ProductFieldsModel->del($where);
        if($result){
            return $this->ajaxSuccess();
        }else{
            return $this->ajaxFail();
        }
    }

    public function export(){

        $titles = [
            '产品名称',
            '产品图片',
            '产品编号',
            '可用库存',
            '预警库存',
            '库存充足数量',
            '产品分类',
        ];

        $fields = '*';

        $where = $this->_where();

        if($this->company){
            $adminUser = request()->user('admin')->toArray();
            $company_id = $adminUser['company_id'];
            $where[$this->model->table.'.company_id'] = $company_id;
        }
        $result = $this->model->getData($where, $fields);
        $result = $this->_hdata($result);

        foreach($result as $val){

            $cellData[] = [
                'product_name'=>$val['product_name'],
                'img_url'=>isset($val->imageInfo->img_url)?$val->imageInfo->img_url:'',
                'product_no'=>$val['product_no'],
                'number'=>$val['number'],
                'warning_number'=>$val['warning_number'],
                'full_number'=>$val['full_number'],
                'category'=>$val->category->cat_name,
            ];
        }

        \Excel::create('数据导出',function($excel) use ($cellData, $titles){
            $title_array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
                'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH'];

            $excel->sheet('score', function($sheet) use ($cellData, $title_array, $titles){

                $sheet->rows($titles);

                foreach ($titles as $key=>$title){
                    $sheet->cell($title_array[$key] . '1', function ($cell) use ($title) {
                        $cell->setValue($title);
                    });
                }

                foreach ($cellData as $line=>$vdata){

                    $eline = $line + 2;
                    $col = 0;
                    foreach ($vdata as $field => $value){
                        switch ($field){
                            case 'img_url':
                                if(is_file(public_path('storage/'.$value)) and file_exists(public_path('storage/'.$value))){
                                    $objDrawing = new PHPExcel_Worksheet_Drawing;
                                    $objDrawing->setPath(public_path('storage/'.$value));
                                    $objDrawing->setCoordinates($title_array[$col] . $eline);
                                    $objDrawing->setHeight(50);
                                    $objDrawing->setOffsetX(100);
                                    $objDrawing->setRotation(100);
                                    $objDrawing->setWorksheet($sheet);
                                }
                                break;
                            default:
                                $sheet->cell($title_array[$col] . $eline, function ($cell) use ($value) {
                                    $cell->setValue($value);
                                });
                                break;
                        }
                        $col ++;

                    }


                }
                $sheet->rows($cellData);
            });
        })->export('xls');

    }

}